import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 30000
})

service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = process.env.VUE_APP_AUTHORIZATION
    config.headers['X-Access-Token'] = process.env.VUE_APP_ACCESSTOKEN
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
  const res = response.data
  if (res.retCode !== '200') {
    if (res.retCode == "500" && res.message == "出现异常：token已失效，请重新登录") {
        removeToken();
        location.reload(); // 刷新重新定位到登录页
    }
    if (res.retCode == "500" && res.message == "出现异常：此账号已被异地登陆，请重新登陆") {
        removeToken();
        location.reload(); // 刷新重新定位到登录页
    }
    if (res.message && res.message.length > 40) {
      res.message = res.message.substring(0, 40) + '....{请查看日志}'
    }
    Message({ message: res.message, type: 'error' })
    return Promise.reject('Error');
  }

  return res
},
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
